package com.miao.hong.fang.util;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.mail.SimpleMailMessage;

import com.miao.hong.fang.user.UserTO;

public class JMSQueueListener implements ServletContextListener{
	
	public void contextInitialized(ServletContextEvent event) {
	
		try {
			
			InitialContext initCtx = new InitialContext();
			Context envContext = (Context) initCtx.lookup("java:comp/env");  
			ConnectionFactory factory = (ConnectionFactory) envContext.lookup("jms/connectionFactory");
			Connection conn = factory.createConnection();
			conn.start();
			
			Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

			Queue register_queue = (Queue) envContext.lookup("jms/register_queue");
			
			MessageConsumer receiver = session.createConsumer(register_queue);
			
			receiver.setMessageListener(new MessageListener(){
				public void onMessage(Message msg) {
					
					ObjectMessage message = (ObjectMessage) msg;
					try {
						UserTO to = (UserTO)message.getObject();
						
						SimpleMailMessage mail = new SimpleMailMessage();
						mail.setSubject("Register Mail");
						mail.setTo(to.getUserEmail());
						mail.setFrom("System");
						mail.setText("Dear " + to.getLoginName() + " you have registered!");
						
						SpringBeansHolder.getInstance().getMailSender().send(mail);
						
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			});
			
		} catch (Exception e) {
			System.out.println("Failed to initialize listener");
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		
	}
}
